package lion.framework.core.task.builder;

import java.util.List;

import org.apache.commons.lang.StringUtils;

import lion.dev.lang.MapJ;
import lion.framework.core.bean.BeanFactory;
import lion.framework.core.conf.Config;
import lion.framework.core.conf.ConfigManager;
import lion.framework.core.task.AutoTaskManager;
import lion.framework.core.task.IAutoTask;
import lion.framework.core.task.ISchedule;
import lion.framework.core.task.ITaskTimerRule;
import lion.framework.core.task.Schedule;
import lion.framework.core.task.anno.ScheduleBuilder;

/**
 * 
 * 默认的Schedule创建器,跟据配置中的参数来进行创建
 * <p>
 * <schedule name="thisisanothertest" rule="default" task=
 * "lion.test.task.TestTask" interval="10" stoponerror="true" />
 * </p>
 * 
 * @author lion
 * @email hl_0074@sina.com
 * @date 2015年8月6日
 */
@ScheduleBuilder("default")
public class DefaultScheduleBuilder implements IScheduleBuilder {

	@Override
	public ISchedule build(MapJ sc) {

		String timerRule = sc.getString("rule", "default");
		String taskType = sc.getString("task");
		String name = sc.getString("name");
		String clusterId = sc.getString("cluster");
		String args = sc.getString("args");

		if (StringUtils.isBlank(name)) { return null; }

		Class<? extends IAutoTask> clazz = AutoTaskManager.getAutoTaskType(taskType);
		if (clazz == null) { return null; }
		IAutoTask task = BeanFactory.create(clazz);

		Class<? extends ITaskTimerRule> ruleClazz = AutoTaskManager.getTaskTimerRuleType(timerRule);
		if (ruleClazz == null) { return null; }

		ITaskTimerRule rule = BeanFactory.create(ruleClazz, sc);

		if (task == null || rule == null) { return null; }

		return new Schedule(name, task, rule, clusterId, args);
	}

	@Override
	public MapJ getScheduleConfig(String scheduleId) {

		Config config = ConfigManager.getConfig("framework");
		List<MapJ> scheduleConf = config.getList("framework.schedule");

		for (MapJ m : scheduleConf) {
			if (StringUtils.equals(scheduleId, m.getString("name"))) { return m; }
		}

		return null;
	}
}
